package com.haulmont.asu.core.app;

import com.haulmont.asu.entity.ProjectThemeBooking;
import com.haulmont.asu.entity.ThemeBookingCommand;
import com.haulmont.cuba.core.EntityManager;
import com.haulmont.cuba.core.Persistence;
import com.haulmont.cuba.core.Transaction;
import com.haulmont.cuba.core.global.Messages;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.annotation.ManagedBean;
import javax.inject.Inject;

/**
 * Author: Sergey42
 * Date: 24.11.13 18:47
 */
@ManagedBean("ext$ReportHelper")
public class ReportHelper {

    private Log log = LogFactory.getLog(ReportHelper.class);

    @Inject
    protected Messages messages;

    @Inject
    protected Persistence persistence;

    public String getThemes(ThemeBookingCommand command) {
        StringBuilder sb = new StringBuilder();

        sb.append("<body>");
        sb.append("<table width = \"100%\">");
        sb.append("<tr>");
        sb.append("<th>").append(message("student")).append("</th>");
        sb.append("<th>").append(message("theme")).append("</th>");
        sb.append("</tr>");

        Transaction tx = persistence.createTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            command = em.find(ThemeBookingCommand.class, command.getId());

            for (ProjectThemeBooking booking : command.getProjectThemeBookings()) {
                sb.append("<tr>");
                sb.append("<td>").append(booking.getDiplomaProject().getDiplomaStudent().getStudent().getName()).append("</td>");
                sb.append("<td>").append(booking.getDiplomaProject().getProjectTheme().getName()).append("</td>");
                sb.append("</tr>");
            }

        } catch (Exception ex) {
            log.error(ExceptionUtils.getStackTrace(ex));
        } finally {
            tx.end();
        }


        sb.append("</table>");
        sb.append("</body>");
        return sb.toString();
    }

    public String message(String key) {
        return messages.getMessage(ReportHelper.class, key);
    }
}
